/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.service.batchno;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.server.common.persistence.Page;
import com.server.common.service.CrudService;
import com.server.modules.sys.utils.BatchNoUtil;
import com.server.modules.sys.dao.batchno.BatchNoDao;
import com.server.modules.sys.entity.batchno.BatchNo;

/**
 * 批次号Service
 * @author 丁光彪
 * @version 2016-10-31
 */
@Service
@Transactional(readOnly = true)
public class BatchNoService extends CrudService<BatchNoDao, BatchNo> {

	public BatchNo get(String id) {
		return super.get(id);
	}
	
	public List<BatchNo> findList(BatchNo batchNo) {
		return super.findList(batchNo);
	}
	
	public Page<BatchNo> findPage(Page<BatchNo> page, BatchNo batchNo) {
		return super.findPage(page, batchNo);
	}
	
	@Transactional(readOnly = false)
	public void save(BatchNo batchNo) {
		super.save(batchNo);
	}
	
	@Transactional(readOnly = false)
	public void delete(BatchNo batchNo) {
		super.delete(batchNo);
	}
	
	 @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	    public String getBatchNoIndex() {
	        BatchNo numb = new BatchNo();
	        numb.setCreatdate(new Date());
	        Date date=new Date();
	        numb.setCreatdate(date);
	        dao.insert(numb);
	        return numb.getId();
	    }

	    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	    public Date getNewCreateDate() {
	    	Page page=new Page<>();
	    	page.setOrderBy(" creatdate desc ");
	    	BatchNo batchNo=new BatchNo();
	    	batchNo.setPage(page);
			List<BatchNo> findList = findList(batchNo);
			if (findList.size() > 0) {
				return findList.get(0).getCreatdate();
			}
	        return new Date();
	    }

	    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	    public String getBatchNO(String bussType) {
	        //当刚好是凌晨同时去查判断是不是已经到第二天了需要删除昨天的数据的时候  会出现并发问题
	        //用户 1可能都判断到已经到第二天了   把表清了 插入一条数据  得到这个生成的id   
	        //然后用户2这个时候也判断到第二天了   把表清了  插入一条数据  得到这个生成的id  
	        //这两个id可能会重复
	        //为啥不能用synchronized ？  
	        //当分布式的时候   有多个jvm   synchronized就完全不起作用了

	        if (!BatchNoUtil.dateCompare(this.getNewCreateDate())) {
	           dao.clearTable();
	        }
	        String index = this.getBatchNoIndex();
	        return BatchNoUtil.creatbussNo(bussType, index);
	    }
	
}